package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    // 处理查询所有部门请求
    // /role/list 目前不带参数, 响应 HTML 格式内容
    @RequiredPermission(name="角色页面", expression = "role:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        // 获取所有部门数据, 存到 Model 中
        model.addAttribute("pageInfo", roleService.query(qo));
        // 找视图
        return "/role/list"; // /WEB-INF/views/role/list.jsp
    }

    // /role/delete?id=id值
    // 处理查询所有部门删除的请求,希望浏览器重新发送一次请求再查询一次
    @RequiredPermission(name="角色删除", expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list"; // 让浏览器再发送一次请求 localhost/role/list
    }

    // 处理保存的请求 /role/saveOrUpdate, POST 携带参数
    @RequiredPermission(name="角色新增/编辑", expression = "role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() != null) {
            roleService.update(role, ids);
        }else {
            roleService.save(role, ids);
        }
        return "redirect:/role/list";
    }

    // 处理去保存或修改请求 /role/input
    @RequiredPermission(name = "角色新增/编辑页面", expression = "role:input")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        model.addAttribute("permissions", permissionService.listAll());
        if (id != null) {
            model.addAttribute("role", roleService.get(id));
        }
        return "role/input";
    }
}
